//
//  PDCurrentLocationManager.m
//  PandaKing
//
//  Created by GiganticWhale on 16/8/29.
//  Copyright © 2016年 PandaOL. All rights reserved.
//

#import "PDCurrentLocationManager.h"
#import <objc/runtime.h>


static char addressComponentKey;                    /**< 地理信息*/
@interface PDCurrentLocationManager()<AMapSearchDelegate,MKMapViewDelegate,CLLocationManagerDelegate>
@property (nonatomic,strong)AMapSearchAPI *search;
@property (nonatomic,strong)MKMapView *mapView;

@property (nonatomic,strong)CLLocationManager *locationManager;
@end

@implementation PDCurrentLocationManager

+ (PDCurrentLocationManager *)sharedLocation {
    static PDCurrentLocationManager *location = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        location = [[PDCurrentLocationManager alloc] init];
    });
    return location;
}

-(void)getCurrentLocationManager:(void(^)(CGFloat lat,CGFloat lng,AMapAddressComponent *addressComponent))block{
    objc_setAssociatedObject(self, &addressComponentKey, block, OBJC_ASSOCIATION_COPY_NONATOMIC);
    [self startLocation];
}

#pragma mark 初始化search
-(void)initSearch{
    self.search = [[AMapSearchAPI alloc]init];
    self.search.delegate = self;
}

#pragma mark 逆地理编码请求
-(void)reGeoctionWithLocation:(CLLocation *)currentLocation{
    AMapReGeocodeSearchRequest *request = [[AMapReGeocodeSearchRequest alloc]init];
    request.location = [AMapGeoPoint locationWithLatitude:currentLocation.coordinate.latitude longitude:currentLocation.coordinate.longitude];
    [self.search AMapReGoecodeSearch:request];
    [self stopLocation];
}

#pragma mark 搜索回调
-(void)searchRequest:(id)request didFailWithError:(NSError *)error{
    NSLog(@"request:%@ ,error :%@",request,error);
}

-(void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response{
    [PDCurrentLocationManager sharedLocation].lat = request.location.latitude;
    [PDCurrentLocationManager sharedLocation].lng = request.location.longitude;
    [PDCurrentLocationManager sharedLocation].addressComponent = response.regeocode.addressComponent;
    
    if (request.location.latitude == 0){
        [PDCurrentLocationManager sharedLocation].lat = 120.188484;
    }
    if (request.location.longitude == 0){
        [PDCurrentLocationManager sharedLocation].lng = 30.2325363;
    }
    
    if (!response.regeocode.addressComponent.province.length){
        response.regeocode.addressComponent.province = @"浙江省";
        response.regeocode.addressComponent.city = @"杭州市";
        
//        @property (nonatomic, copy)   NSString         *citycode; //!< 城市编码
//        @property (nonatomic, copy)   NSString         *district; //!< 区
//        @property (nonatomic, copy)   NSString         *adcode; //!< 区域编码
//        @property (nonatomic, copy)   NSString         *township; //!< 乡镇街道
//        @property (nonatomic, copy)   NSString         *towncode; //!< 乡镇街道编码
//        @property (nonatomic, copy)   NSString         *neighborhood; //!< 社区
//        @property (nonatomic, copy)   NSString         *building; //!< 建筑
//        @property (nonatomic, strong) AMapStreetNumber *streetNumber; //!< 门牌信息
//        @property (nonatomic, strong) NSArray<AMapBusinessArea *> *businessAreas; //!< 商圈列表 AMapBusinessArea 数组
    }
    
    
    void(^block)(CGFloat lat,CGFloat lng,AMapAddressComponent *addressComponent) = objc_getAssociatedObject(self, &addressComponentKey);
    if (block){
        block(request.location.latitude,request.location.longitude,response.regeocode.addressComponent);
    }
}


- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
    CLLocation *newLocation = userLocation.location;
    [self initSearch];
    [self reGeoctionWithLocation:newLocation];
}

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{
    switch (status) {
        case kCLAuthorizationStatusDenied :{
            UIAlertView *tempA = [[UIAlertView alloc]initWithTitle:@"提醒" message:@"请在设置-隐私-定位服务中开启定位功能！" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [tempA show];
        } break;
        case kCLAuthorizationStatusNotDetermined :
            if ([_locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
                [_locationManager requestAlwaysAuthorization];
                
            }
            break;
        case kCLAuthorizationStatusRestricted:{
            UIAlertView *tempA = [[UIAlertView alloc]initWithTitle:@"提醒" message:@"定位服务无法使用！" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [tempA show];
        } default:
            [self.locationManager startUpdatingLocation];
            break;
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    CLLocation *currentLocation = [locations lastObject];
    [self initSearch];
    self.locationManager = manager;
    [self reGeoctionWithLocation:currentLocation];
}




#pragma mark - location
-(void)startLocation {
    if (IS_IOS8_LATER){
        _locationManager = [[CLLocationManager alloc]init];
        _locationManager.delegate = self;
        _locationManager.distanceFilter = 200;
        _locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
    } else {
        if (_mapView) {
            _mapView = nil;
        }
        
        _mapView = [[MKMapView alloc] init];
        _mapView.delegate = self;
        _mapView.showsUserLocation = YES;
    }
}

-(void)stopLocation {
    if (IS_IOS8_LATER){
        _locationManager = nil;
    } else {
        _mapView.showsUserLocation = NO;
        _mapView = nil;
    }
}

- (void)mapView:(MKMapView *)mapView didFailToLocateUserWithError:(NSError *)error {
    [self stopLocation];
}



@end
